﻿using Autofac;
using System;
using System.Web;
using System.Web.Optimization;
using System.Web.Routing;
using Autofac.Integration.Web;
using Microsoft.AspNet.FriendlyUrls;
using CacheWebForm.QCache;
using CacheWebForm.Services;
using System.Reflection;

namespace CacheWebForm
{
    public class Global : HttpApplication,IContainerProviderAccessor
    {
        // Provider that holds the application container.
        static IContainerProvider _containerProvider;

        // Instance property that will be used by Autofac HttpModules
        // to resolve and inject dependencies.
        public IContainerProvider ContainerProvider
        {
            get { return _containerProvider; }
        }
        ///// <summary>
        ///// 后添加的友好路由
        ///// </summary>
        ///// <param name = "routes" ></ param >
        ////public static void RegisterRoutes(RouteCollection routes)
        ////{
        ////    var settings = new FriendlyUrlSettings();
        ////    settings.AutoRedirectMode = RedirectMode.Permanent;
        ////    routes.EnableFriendlyUrls(settings);
        ////}

        void Application_Start(object sender, EventArgs e)
        {
           
            // 在应用程序启动时运行的代码
             RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            //出现异常的处理
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            #region 使用Autofac
            // Build up your application container and register your dependencies.
            var builder = new ContainerBuilder();
            builder.RegisterType<DateTimeService>().As<IDateTimeService>();
            var assembly = this.GetType().GetTypeInfo().Assembly;
            // .NetFrameWork 4.5不支持AOP
            //builder.RegisterAssemblyTypes(assembly)
            //       .Where(type => typeof(IDateTimeService).IsAssignableFrom(type) && !type.GetTypeInfo().IsAbstract)
            //       .AsImplementedInterfaces()
            //       .InstancePerLifetimeScope()
            //       .EnableInterfaceInterceptors()
            //       .InterceptedBy(typeof(QCachingInterceptor));


            // Once you're done registering things, set the container
            // provider up with your registrations.
            _containerProvider = new ContainerProvider(builder.Build());
            #endregion
            // Standard web forms startup.
            //RegisterRoutes(RouteTable.Routes);
        }
        void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Exception ex = e.ExceptionObject as Exception;
            if (ex != null)
            {
                string msg = ex.Message;
                string stack = ex.StackTrace;
                //写入日志文件
            }
        }

    }
}